package com.itheima.controller;

import com.itheima.pojo.Dept;
import com.itheima.pojo.Result;
import com.itheima.service.DeptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/depts")
public class DeptController {
    /*
    * 自己创建的对象不被IOC容器管理，想向这个deptService对象调用的方法中注入deptMapper对象，
    * 无法注入，所以程序运行时提示this.deptMapper is null*/

//    private DeptService deptService = new DeptServiceImpl();

    @Autowired
    private DeptService deptService ;

    //====================================查询========================================
//    @RequestMapping(value = "/depts",method = RequestMethod.GET)
    @GetMapping
    public Result list() {

        List<Dept> deptList = deptService.getDeptList();
        return Result.success(deptList);
    }


    //====================================删除========================================

    //通过原始的 `HttpServletRequest` 对象获取请求参数**
/*    @DeleteMapping("/depts")
    public Result delete(HttpServletRequest request){
        String idStr = request.getParameter("id");
        int id = Integer.parseInt(idStr);
        deptService.deleteDeptById(id);
        return Result.success();
    }*/

    //通过Spring提供的 `@RequestParam` 注解，将请求参数绑定给方法形参
    //一旦加了@RequestParam注解，该参数必须传递，因为默认required为true，required设置为false则为可传可不传
/*    @DeleteMapping("/depts")
    public Result delete(@RequestParam("id") Integer deptId) {
        deptService.deleteDeptById(deptId);
        return Result.success();
    }*/

    //如果接收到的参数和前端传递过来的参数名称一致，则@RequestParam注解也可省略
    @DeleteMapping
    public Result deleteDept(@RequestParam(value = "id",defaultValue = "1",required = true) Integer id) {
        deptService.deleteDeptById(id);
        return Result.success();
    }

    //====================================新建========================================

    //RequestBody   JSON格式数据转为Java对象
    @PostMapping
    public Result putDept(@RequestBody Dept dept) {
//        System.out.println(map.get("name"));
        deptService.saveDept(dept.getName());
        return Result.success();
    }

    //====================================修改========================================

    @GetMapping("/{id}")
    public Result getDeptById(@PathVariable Integer id){
        Dept dept = deptService.getById(id);
        return Result.success(dept);
    }

    @PutMapping
    public Result updateDept(@RequestBody Dept dept) {
        //日志技术
        log.debug("我是debug");
        log.info("我是info");

        System.out.println("修改的部门数据:" + dept);
        deptService.updateDept(dept);
        return Result.success();
    }




}
